// api/dataAPI.js
const API_BASE_URL = 'http://localhost:8800';

class DataAPI {
    constructor() {
        this.baseURL = API_BASE_URL;
    }

    async request(endpoint, options = {}) {
        try {
            const url = `${this.baseURL}${endpoint}`;
            console.log(`🌐 API请求: ${url}`);

            const config = {
                mode: 'cors',
                credentials: 'omit',
                headers: {
                    'Content-Type': 'application/json',
                    ...options.headers,
                },
                ...options,
            };

            if (options.body && typeof options.body === 'object') {
                config.body = JSON.stringify(options.body);
            }

            const response = await fetch(url, config);

            console.log('响应状态:', response.status, response.statusText);

            if (!response.ok) {
                let errorText = '无响应内容';
                try {
                    errorText = await response.text();
                    console.error('错误响应内容:', errorText);
                } catch (e) {
                    console.error('无法读取错误响应:', e);
                }
                throw new Error(`HTTP error! status: ${response.status}, response: ${errorText}`);
            }

            const data = await response.json();
            console.log(`✅ API响应成功:`, data);
            return data;
        } catch (error) {
            console.error(`❌ API请求失败: ${endpoint}`, error);
            throw error;
        }
    }

    // 获取场景数据
    async getSceneData(scene, userId) {
        return this.request(`/data/by-user?scene=${scene}&userId=${userId}`);
    }

    // 获取警报数据 - 获取所有数据
    async getAlerts(userId) {
        try {
            console.log('🚨 获取所有警报数据API调用:', { userId });

            const rawData = await this.request(`/data/alert/by-user?userId=${userId}`);
            console.log('📊 原始警报数据:', rawData);

            // 处理响应数据格式
            let alerts = [];

            if (rawData && rawData.success) {
                alerts = rawData.data || [];
            } else if (Array.isArray(rawData)) {
                alerts = rawData;
            } else if (rawData && typeof rawData === 'object') {
                alerts = rawData.alerts || rawData.data || [];
            }

            console.log('📋 获取到的所有警报数据，总数:', alerts.length);

            // 标准化警报格式（返回所有数据）
            const standardizedAlerts = this.standardizeAlerts(alerts);
            console.log('✅ 标准化后的所有警报数据:', standardizedAlerts);

            return {
                success: true,
                data: standardizedAlerts,
                message: '获取警报数据成功',
                totalCount: standardizedAlerts.length
            };

        } catch (error) {
            console.error('❌ 获取警报数据失败:', error);
            return {
                success: false,
                data: [],
                message: error.message || '获取警报数据失败'
            };
        }
    }

    // 标准化警报格式
    standardizeAlerts(alerts) {
        if (!Array.isArray(alerts)) {
            console.warn('⚠️ 警报数据不是数组:', alerts);
            return [];
        }

        return alerts.map(alert => {
            // 统一字段名称，保持原始 board_id
            return {
                id: alert.id || alert.alert_id || Math.random().toString(36).substr(2, 9),
                board_id: alert.board_id || alert.boardId || null,
                type: alert.type || alert.alert_type || 'unknown',
                message: alert.message || alert.alert_message || alert.content || '无报警信息',
                timestamp: alert.timestamp || alert.create_time || alert.time || new Date().toISOString(),
                severity: alert.severity || alert.level || 'medium',
                status: alert.status || 'active'
            };
        });
    }

    // 获取按 board_id 分组的警报统计
    async getAlertsByBoard(userId) {
        try {
            const alertsResponse = await this.getAlerts(userId);

            if (!alertsResponse.success) {
                return alertsResponse;
            }

            const alerts = alertsResponse.data;

            // 按 board_id 分组
            const alertsByBoard = {};
            alerts.forEach(alert => {
                const boardId = alert.board_id;
                if (!alertsByBoard[boardId]) {
                    alertsByBoard[boardId] = [];
                }
                alertsByBoard[boardId].push(alert);
            });

            console.log('📊 按 board_id 分组的警报:', alertsByBoard);

            return {
                success: true,
                data: alertsByBoard,
                message: '获取分组警报数据成功'
            };

        } catch (error) {
            console.error('❌ 获取分组警报数据失败:', error);
            return {
                success: false,
                data: null,
                message: error.message || '获取分组警报数据失败'
            };
        }
    }

    // 获取特定 board_id 的警报
    async getAlertsByBoardId(userId, boardId) {
        try {
            const alertsResponse = await this.getAlerts(userId);

            if (!alertsResponse.success) {
                return alertsResponse;
            }

            const allAlerts = alertsResponse.data;
            const filteredAlerts = allAlerts.filter(alert => alert.board_id === boardId);

            console.log(`📋 board_id=${boardId} 的警报数据:`, filteredAlerts);

            return {
                success: true,
                data: filteredAlerts,
                message: `获取 board_id=${boardId} 的警报数据成功`,
                count: filteredAlerts.length
            };

        } catch (error) {
            console.error(`❌ 获取 board_id=${boardId} 的警报数据失败:`, error);
            return {
                success: false,
                data: [],
                message: error.message || `获取 board_id=${boardId} 的警报数据失败`
            };
        }
    }

    // 获取农场概览数据
    async getFarmOverview(userId) {
        return this.request(`/data/by-user?scene=home&userId=${userId}`);
    }

    // 获取环境数据
    async getEnvironmentalData(userId) {
        return this.request(`/data/by-user?scene=home&userId=${userId}`);
    }

    // 获取设备状态
    async getDeviceStatus(userId) {
        return this.request(`/data/by-user?scene=home&userId=${userId}`);
    }
}

export default new DataAPI();